<template>
	<view class="UserInfo">
		<view class="UserInfo-header">
			<DistributionNavBar title="个人信息" rgb="#fff">
				<template slot="left">
					<image :src="BackIcon" @click="goBack" />
				</template>
			</DistributionNavBar>
		</view>

		<view class="UserInfo-main">
			<view class="UserInfo-main-head" @click="editAvatar">
				<image :src="userInfo.headUrl" class="UserInfo-main-head-avatar" />

				<text class="UserInfo-main-head-txt">点击更换头像</text>
			</view>
			<view class="UserInfo-main-name">
				<input placeholder="请输入昵称" v-model.trim="userInfo.nickName" />
				<text class="UserInfo-main-head-txt">{{ nickNameHint }}</text>
			</view>

			<view class="UserInfo-main-footer">
				<button
					@click="submitSave"
					:loading="isLoading"
					:disabled="isLoading || isNickName"
					:class="{
						active: isLoading || isNickName
					}"
				>
					保存
				</button>
			</view>
		</view>

		<KpsImageCutter @ok="onok" @cancel="oncancle" :url="previewUrl" :blob="false" />
	</view>
</template>

<script>
import { mapMutations } from 'vuex';
import { setUserInfo } from '@/api/login';
import { defaultImageUrl } from '@/utils';
import EncapsulationUpload from '@/plugIn/upload';

import KpsImageCutter from '@/components/distributionKpsImageCutter';
import DistributionNavBar from '@/components/distributionNavBar/indeHome';

const nickNameHint = Object.freeze('2-12个字符，中文、英文、数字');
const BackIcon = Object.freeze(`${defaultImageUrl}help/icon_navbar_back.png`);

export default {
	name: 'UserInfo',

	data() {
		return {
			BackIcon,
			nickNameHint,

			userInfo: {},
			previewUrl: '',

			isLoading: false,
			uploadStatusFileList: []
		};
	},

	created() {
		const userInfo = this.$store.state.system.userInfo;

		this.userInfo = {
			...userInfo
		};
	},

	computed: {
		isNickName() {
			const {
				userInfo: { nickName = '' }
			} = this;

			return nickName.trim() === '';
		},

		currentAvatarInfo() {
			const { uploadStatusFileList } = this;

			return uploadStatusFileList.find((item) => item.type === 'image')?.list?.[0] || {};
		}
	},

	watch: {
		uploadStatusFileList: {
			deep: true,
			handler(params) {
				const {
					userInfo: { headUrl }
				} = this;
				if (!params.length) {
					return;
				}

				const { status, tempFilePath } = this.currentAvatarInfo || {};

				if (status === 'success') {
					this.submitSave();
					return;
				}

				if (tempFilePath === headUrl) {
					return;
				}

				this.previewUrl = tempFilePath;
			}
		}
	},

	onLoad() {
		this.upload = new EncapsulationUpload({
			that: this,
			isReplace: true,
			autoupload: false,
			statusNumber: {
				maxImage: 1
			},
			requestParams: {
				type: 1
			}
		});
	},

	methods: {
		...mapMutations(['changeUserInfo']),

		onok({ path }) {
			this.previewUrl = '';
			this.userInfo.headUrl = path;
		},

		oncancle() {
			this.previewUrl = '';
		},

		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},

		editAvatar() {
			this.upload.openPhotoAlbum();
		},

		submitSave() {
			const {
				chkstrlen,
				currentAvatarInfo,
				uploadStatusFileList,
				upload: { ALYOSSConfig },
				userInfo: { nickName, headUrl, ...otherParams }
			} = this;

			if (!chkstrlen()) {
				return;
			}

			this.isLoading = true;

			const isLength = uploadStatusFileList.length;
			const { EndPoint, originalPath } = ALYOSSConfig;

			const params = Object.assign(
				{ nickName },
				isLength && {
					headUrl: `${EndPoint}/${originalPath}${currentAvatarInfo.name}`
				}
			);

			if (isLength && currentAvatarInfo.status !== 'success') {
				this.uploadStatusFileList = [
					{
						type: 'image',
						list: [
							{
								...currentAvatarInfo,
								previewUrl: headUrl,
								tempFilePath: headUrl
							}
						]
					}
				];

				this.upload.singleAgainUpload({
					index: 0,
					type: 'image'
				});
				return;
			}

			setUserInfo(params).then((res) => {
				const { code, message } = res;

				this.isLoading = false;
				const isError = code !== 200;

				uni.showToast({
					mask: true,
					icon: 'none',
					title: isError ? message : '操作成功',
					success: () => {
						if (isError) {
							return;
						}

						this.changeUserInfo({
							headUrl,
							...params,
							...otherParams
						});

						setTimeout((e) => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					}
				});
			});
		},

		chkstrlen() {
			const {
				nickNameHint,
				userInfo: { nickName }
			} = this;
			let strlen = 0;

			for (let i = 0; i < nickName.length; i++) {
				if (nickName.charCodeAt(i) > 255) {
					strlen += 2;
					continue;
				}
				++strlen;
			}

			if (strlen < 2 || strlen > 12) {
				uni.showToast({
					icon: 'none',
					title: nickNameHint
				});
				return false;
			}

			return true;
		}
	},

	components: {
		KpsImageCutter,
		DistributionNavBar
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.UserInfo {
	&-header {
		image {
			width: 40rpx;
			height: 40rpx;
			padding: 20rpx;
			margin-left: -20rpx;
		}
	}
}

.UserInfo-main {
	background: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 32rpx 0 40rpx 0;

	color: #999;
	font-size: 24rpx;

	&-head {
		display: flex;
		flex-direction: column;
		align-items: center;

		&-avatar {
			width: 160rpx;
			height: 160rpx;
			border-radius: 50%;
		}

		&-txt {
			padding-top: 16rpx;
			font-weight: 400;
		}
	}

	&-name {
		margin-top: 64rpx;

		input {
			color: #333;
			font-size: 28rpx;

			width: 654rpx;
			height: 84rpx;
			padding-left: 32rpx;
			background: #f6f6f6;
			border-radius: 16rpx;
		}

		.UserInfo-main-head-txt {
			display: block;
			padding-left: 32rpx;
		}
	}

	&-footer {
		width: 100%;
		padding: 0 40rpx;
		margin-top: 60rpx;

		button {
			@include Db_commonButton(80rpx, 24rpx);
		}
	}
}
</style>
